package site.timers.chat.util.netty;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;

/**
 * @Classname GroupChatServerWebSocketHandler
 * @Description TODO
 * @Version 1.0.0
 * @Date 2025/8/12 18:31
 * @Author twl
 */
@Slf4j
public class GroupChatServerWebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    // 用于管理所有活跃的Channel
    private static final ChannelGroup CHANNEL_GROUP = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    /**
     * 当建立连接时，第一个被执行
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        //加入聊天
        CHANNEL_GROUP.add(channel);
        log.info("【{}】 {} 加入聊天室", ctx.channel().remoteAddress(), LocalDateTimeUtil.formatNormal(LocalDateTime.now()));
    }


    /**
     * 表示channel处于一个活跃的状态
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("【{}】 {} 上线了 ~", ctx.channel().remoteAddress(), LocalDateTimeUtil.formatNormal(LocalDateTime.now()));
    }

    /**
     *  表示channel处于不活动的状态
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info("【{}】 {} 离线了 ~", ctx.channel().remoteAddress(), LocalDateTimeUtil.formatNormal(LocalDateTime.now()));
    }


    /**
     * channel断开连接会被触发
     */
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        log.info("【{}】 {} 离开了 ~", ctx.channel().remoteAddress(), LocalDateTimeUtil.formatNormal(LocalDateTime.now()));
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame frame) throws Exception {
        String text = frame.text();
        log.info("收到消息: {}", text);

        try {
            // 解析JSON消息
            JSONObject json = JSON.parseObject(text);
            String type = json.getString("type");
            String sender = json.getString("sender");
            String message = json.getString("message");

            // 构建响应消息
            JSONObject response = new JSONObject();
            response.put("type", type);
            response.put("sender", sender);
            response.put("message", message);
            response.put("timestamp", System.currentTimeMillis());

            // 广播消息给所有客户端
            // CHANNEL_GROUP.writeAndFlush(new TextWebSocketFrame(response.toJSONString()));

            // 广播消息给所有客户端，排除发送端
            CHANNEL_GROUP.stream()
                    .filter(channel -> channel != ctx.channel())
                    .forEach(channel -> channel.writeAndFlush(new TextWebSocketFrame(response.toJSONString())));
        } catch (Exception e) {
            log.error("消息处理错误", e);
            ctx.writeAndFlush(new TextWebSocketFrame("{\"error\":\"消息格式错误\"}"));
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("WebSocket处理异常", cause);
        ctx.close();
    }
}